//
//  YDAdvertViewController.m
//  PeiZiWangBei
//
//  Created by 巨彦新 on 2017/12/12.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDAdvertViewController.h"
#import "YDWebProgressLayer.h"
#import "YDRechargeSuccessViewController.h"
#import "YDVerticalStockBuyController.h"

#import <WebKit/WebKit.h>


static NSString *const CallBack = @"callback";
static NSString *const ReceiveSuccess = @"ReceiveSuccess";
static NSString *const GetUserId = @"GetUserId";

@interface YDAdvertViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomic, strong)WKWebView *webview;
@property (nonatomic, strong) YDWebProgressLayer *webProgressLayer;  //  进度条

/**
 加载数据的菊花
 */
@property (nonatomic,weak) UIActivityIndicatorView *activityView;

@end

@implementation YDAdvertViewController

-(UIActivityIndicatorView *)activityView
{
    if (_activityView == nil) {
        UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] init];
        [self.view addSubview:activityView];
        activityView.hidesWhenStopped = YES;
        activityView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [activityView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(15, 15));
        }];
        _activityView = activityView;
    }
    return _activityView;
}

-(void)dealloc
{
    
    [_webProgressLayer closeTimer];
    [_webProgressLayer removeFromSuperlayer];
    
    _webProgressLayer = nil;
}

#pragma mark - view life
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNav];
    [self.view addSubview:self.webview];
    
    if (self.isJD) {
        self.extendedLayoutIncludesOpaqueBars = YES;
    }
    
    DDLog(@"跳转网页的url==%@",self.urlStr);
    
    if (self.urlStr.length) {
        
        
        NSString *charactersToEscape = @"^";
        NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
        
        NSString *encodedUrl = [self.urlStr stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:encodedUrl]];
        
        
        
        
        [request setValue:[[SYUserDataManger sharedInstance] getUserToken] forHTTPHeaderField:@"Authorization"];
        [self.webview loadRequest:request];
    }
    
    
    [self activityView];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.webview.configuration.userContentController addScriptMessageHandler:self name:CallBack];
    [self.webview.configuration.userContentController addScriptMessageHandler:self name:ReceiveSuccess];
    [self.webview.configuration.userContentController addScriptMessageHandler:self name:GetUserId];
    [self.webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    @try {
        //防止手势导致的提前移除监听再移除导致的崩溃
        [_webview.configuration.userContentController removeScriptMessageHandlerForName:CallBack];
        [_webview.configuration.userContentController removeScriptMessageHandlerForName:ReceiveSuccess];
        [_webview.configuration.userContentController removeScriptMessageHandlerForName:GetUserId];
        [_webview removeObserver:self forKeyPath:@"estimatedProgress"];
    }
    @catch (NSException *exception) {
        DDLog(@"====web errror===%@",exception.description);
    }
    
    
    
}


-(void)setNav
{
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    _webProgressLayer = [[YDWebProgressLayer alloc] init];
    _webProgressLayer.frame = CGRectMake(0, 42, LKScreenW, 2);
    
    [self.navigationController.navigationBar.layer addSublayer:_webProgressLayer];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageWIthOriginalImage:@"nav-all-back"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    
}

#pragma mark - WKScriptMessageHandler js原生交互的代理方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:CallBack]) {
        
        DDLog(@"js传过来的信息%@",message.body);
        
        NSString *msg = [message.body objectForKey:@"result"];
        if ([msg isEqualToString:@"已支付"]) {
            //更新本地余额
            [[SYUserDataManger sharedInstance] currentAccountBalanceChangeWithUsedAmountString:self.money IsAdd:YES];
            
            YDRechargeSuccessViewController *vc = [[YDRechargeSuccessViewController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage
                                                                text:msg
                                                          isExistNav:YES];
        }
        
    }
    else if ([message.name isEqualToString:ReceiveSuccess])
    {
        BOOL isToken = [[message.body objectForKey:@"isToken"] boolValue];
        //用户领取体验金2000成功回调
        if (isToken) {
            //默认平安银行
            YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
            vc.stockCode = @"000001";
            vc.stockName = @"平安银行";
            vc.isActivity = YES;
            vc.isNormal = YES;
            vc.hidesBottomBarWhenPushed = YES;
            
            [self.navigationController pushViewController:vc animated:YES];
        }else
        {
            //没登录去注册
            [self presentLoginVC];
        }
        
    }else if ([message.name isEqualToString:GetUserId])
    {
        NSNumber *user_id = [SYUserDataManger sharedInstance].getUser_Id;
        NSString *JSResult = nil;
        
        if ([user_id boolValue]) {
            JSResult   = [NSString stringWithFormat:@"getAppUserId('%@')",user_id];
        }else
        {
            JSResult = [NSString stringWithFormat:@"getAppUserId()"];
        }
        
        
        [self.webview evaluateJavaScript:JSResult completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        }];
        
    }
}

#pragma mark - WKNavigationDelegate 页面加载的代理方法


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [_webProgressLayer startLoad];
}

-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    if (!self.title.length) {
        [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
            
            self.title = response;
            
            
        }];
    }
    
    
    [_webProgressLayer finishedLoadWithError:nil];
}

-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [_webProgressLayer finishedLoadWithError:error];
}


#pragma mark - H5弹窗要实现 要不不弹窗
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - H5 tel标签拨打电话问题
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    UIApplication *app = [UIApplication sharedApplication];
    // 打电话
    if ([scheme isEqualToString:@"tel"]) {
        if ([app canOpenURL:URL]) {
            [app openURL:URL];
            // 一定要加上这句,否则会打开新页面
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    //    // 打开appstore
    //    if ([url.absoluteString containsString:@"ituns.apple.com"]) {
    //        if ([app canOpenURL:url]) {
    //            [app openURL:url];
    //            decisionHandler(WKNavigationActionPolicyCancel);
    //            return;
    //        }
    //    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - getter
- (WKWebView *)webview
{
    if (!_webview) {
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        WKPreferences *preferences = [WKPreferences new];
        preferences.javaScriptCanOpenWindowsAutomatically = YES;
        // preferences.minimumFontSize = 40.0;
        configuration.preferences = preferences;
        _webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.tabBarController.tabBar.height) configuration:configuration];
        _webview.UIDelegate = self;
        _webview.navigationDelegate = self;
        
        
    }
    return _webview;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == _webview && [keyPath isEqualToString:@"estimatedProgress"])
    {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        
        if (newprogress == 1) {
            [self.activityView stopAnimating];
        }else{
            [self.activityView startAnimating];
        }
    }
}
- (void)presentLoginVC
{
    YDLoginController *loginVC = [[YDLoginController alloc] init];
    loginVC.loginStyle = Login_Present;
    YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:baseNav animated:YES completion:nil];
}
- (void)goBack
{
    
    if ([self.webview canGoBack] && self.isJD) {
        [self.webview goBack];
    }else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

@end
